package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import model.College;
import model.Group;
import dataLayer.DAOGroup;
import dataLayer.DBconnect;
import types.ConsoleType;
import view.PanelAddGroup;
import view.PanelGroupList;
import view.PanelHolder;

public class AddGroup extends DBconnect implements ActionListener {

	private String Group_Name;

	private PanelAddGroup PAGform;

	public AddGroup(PanelAddGroup PAGform) {
		this.PAGform = PAGform;

	}

	// Check on fields for addGroup and Error messages in console
	public void actionPerformed(ActionEvent e) {
		openConn();
		Group_Name = PAGform.getJTname().getText();
		Group g = new Group(Group_Name.toUpperCase(), null);
		if (e.getActionCommand().equals("Opslaan")) {
			String message = null;
			ConsoleType type = null;
			try {

				if (Group_Name.equals("")) {
					message = "Er is nog geen klassennaam ingevuld.";
					type = ConsoleType.ERROR;
				}

				else if (!College.getInstance().addGroup(g)) {
					message = "Deze klas bestaat al.";
					type = ConsoleType.ERROR;
				}

				else if (Group_Name.length() > 10) {
					message = "Een klas mag maximaal 10 tekens bevatten.";
					type = ConsoleType.ERROR;
				} else {
				// adds the group to the database
					College.getInstance().addGroup(g);
					DAOGroup dbG = DAOGroup.getInstance();
					dbG.insertGroup(g);

					PanelHolder ph = PanelHolder.getInstance();
					ph.remove(PAGform);
					ph.add(PanelGroupList.getInstance());
					ph.repaint();
					ph.revalidate();
					message = Group_Name + " is opgeslagen.";
					type = ConsoleType.SUCCESS;
				}
				Console.getInstance().setConsole(message, type);

			} catch (Exception e2) {
				e2.printStackTrace();
				System.err.println("error");
			}
		}
	}

}
